package com.example.transaction.sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.transaction.common.vo.Result;
import com.example.transaction.sys.entity.*;
import com.example.transaction.sys.service.ILeavedMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/sys/leavedMessage")
public class LeavedMessageController {
    @Autowired
    private ILeavedMessageService leavedMessageService;

    /**
     * 查找物品下面的所有留言
     * @param itemID
     * @return
     */
    @Cacheable(value = "leavedMessages",key = "#itemID")
    @GetMapping("/{itemID}")
    public Result<List<LeavedMessage>> getMessageByItemId(@PathVariable("itemID")String itemID){
        LambdaQueryWrapper<LeavedMessage> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasLength(itemID),LeavedMessage::getItemID,itemID);
        List<LeavedMessage> leavedMessage=leavedMessageService.list(wrapper);
        return Result.success(leavedMessage);
    }


    /**
     * 新增留言
     * @param leavedMessage
     * @return
     */
    @CacheEvict(value = "leavedMessages", allEntries = true)
    @PostMapping("/addLeavedMessage")
    public Result<?>addLeavedMessage(@RequestBody LeavedMessage leavedMessage){
        try {
            leavedMessageService.save(leavedMessage);
        }catch (Exception e){
            return Result.fail("新增失败");
        }
        return Result.success("新增留言成功");
    }

    /**
     * 根据留言id删除留言
     * @param leavedMessageID
     * @return
     */
    @CacheEvict(value = "leavedMessages", allEntries = true)
    @DeleteMapping("/{leavedMessageID}")
    public Result<Item>deleteItemById(@PathVariable("leavedMessageID")Integer leavedMessageID){
        leavedMessageService.removeById(leavedMessageID);
        return Result.success("删除留言成功");
    }
}
